using System.IO;
using System.Windows.Media.Imaging;
using AndyPike.Experiments.Fluent.Interfaces;

namespace AndyPike.Experiments.Fluent.Commands
{
    public class SaveAsJpegCommand : ICommand
    {
        private readonly string path;
        private readonly int qualityLevel;

        public SaveAsJpegCommand(string path, int qualityLevel)
        {
            GuardAgainst.ArgumentNullOrEmpty(path, "path");
            GuardAgainst.ArgumentOutsideRange(qualityLevel, "qualityLevel", 1, 100);

            this.path = path;
            this.qualityLevel = qualityLevel;
        }

        public WriteableBitmap Execute(WriteableBitmap image)
        {
            GuardAgainst.ArgumentNull(image, "image");

            Directory.CreateDirectory(Path.GetDirectoryName(path));

            var encoder = new JpegBitmapEncoder { QualityLevel = qualityLevel };
            encoder.Frames.Add(BitmapFrame.Create(image));

            using (var stream = new FileStream(path, FileMode.Create))
            {
                encoder.Save(stream);
            }

            return image;
        }
    }
}